$(function () {
    // 全局变量存储上传的文件
    let uploadedFile = null;

    // 初始化图表
    echart_1([], [], []); // 初始化空图表
    echart_2(0, 0, 0);   // 初始化空图表
    echart_3([], [], [], [], []); // 初始化空图表

    // 文件选择事件处理
    document.getElementById('fileInput').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;

        // 验证文件类型
        if (!file.name.endsWith('.csv')) {
            alert('错误：请上传CSV格式的文件');
            return;
        }

        uploadedFile = file;
        alert(`文件 "${file.name}" 已选择，可以开始预测`);
        document.getElementById('predictBtn').disabled = false;
    });

    // 显示状态消息
    function showStatusMessage(message, type) {
        const statusElement = document.getElementById('statusMessage');
        if (statusElement) {
            statusElement.textContent = message;
            statusElement.className = `status-message ${type}`;
            statusElement.style.display = 'block';

            // 3秒后自动隐藏
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 3000);
        }
    }

    // 上传文件到服务器
    async function uploadFile() {
        if (!uploadedFile) {
            showStatusMessage('请先选择文件', 'error');
            return null;
        }

        const formData = new FormData();
        formData.append('file', uploadedFile);

        try {
            const response = await fetch('http://127.0.0.1:5000/upload', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`上传失败: ${response.statusText}`);
            }

            const result = await response.json();
            showStatusMessage('文件上传成功', 'success');
            return result;
        } catch (error) {
            console.error('上传错误:', error);
            showStatusMessage(`上传错误: ${error.message}`, 'error');
            return null;
        }
    }

    // 获取预测数据
    window.fetchPredictionData = async function() {
        // 首先上传文件
        const uploadResult = await uploadFile();
        if (!uploadResult) return;

        try {
            const loadingMessage = alert('正在预测，请稍等...');
            // 使用 fetch API 发起 GET 请求
            const response = await fetch('http://127.0.0.1:5000/predict');

            // 检查响应状态码，确保请求成功
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 解析响应 JSON 数据
            const data = await response.json();
            console.log('Prediction Data:', data);
            alert('预测完成！');


            // 更新图表数据
            echart_1(data.chart1.high_temps, data.chart1.low_temps, data.chart1.dates);

            // 计算温度分布
            const tempDistribution = countTemperatureDistribution(
                data.table.map(item => item.avg)
            );
            echart_2(
                tempDistribution.high,
                tempDistribution.normal,
                tempDistribution.low
            );

            // 更新训练曲线图
            echart_3(
                data.chart3.train_loss,
                data.chart3.test_loss,
                data.chart3.train_rmse,
                data.chart3.test_rmse,
                data.chart3.epochs
            );
            fillTableData(data.table);

        } catch (error) {
            // 捕获并处理任何错误
            console.error('Error fetching prediction data:', error);
            alert('获取预测数据失败: ' + error.message);
        }
    };
    // 填充表格数据
function fillTableData(tableData) {
    const tableBody = document.getElementById('table-body');
    if (!tableBody) return;

    // 清空表格
    tableBody.innerHTML = '';

    // 填充数据
    tableData.forEach(item => {
        const row = document.createElement('tr');

        const highTempCell = document.createElement('td');
        highTempCell.textContent = item.high;
        row.appendChild(highTempCell);

        const lowTempCell = document.createElement('td');
        lowTempCell.textContent = item.low;
        row.appendChild(lowTempCell);

        const avgTempCell = document.createElement('td');
        avgTempCell.textContent = item.avg;
        row.appendChild(avgTempCell);

        tableBody.appendChild(row);
    });
}


    // 计算温度分布
    function countTemperatureDistribution(averages) {
        const result = {
            low: 0,
            normal: 0,
            high: 0
        };

        for (const temp of averages) {
            if (temp < 10) {
                result.low++;
            } else if (temp > 10 && temp <= 25) {
                result.normal++;
            } else {
                result.high++;
            }
        }

        return result;
    }

    function echart_1(highTemps, lowTemps, dates) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('chart_1'));

        var legendData = ['高温', '低温'];
        var title = "温度预测趋势";
        var serieData = [];
        var metaDate = [
            highTemps,
            lowTemps
        ];

        for (var v = 0; v < legendData.length; v++) {
            var serie = {
                name: legendData[v],
                type: 'line',
                symbol: "circle",
                symbolSize: 10,
                data: metaDate[v]
            };
            serieData.push(serie);
        }

        var colors = ["#036BC8", "#2EF7F3"];
        var option = {
            title: {
                text: title,
                textAlign: 'left',
                textStyle: {
                    color: "#fff",
                    fontSize: "12",
                    fontWeight: "bold"
                }
            },
            legend: {
                show: true,
                left: "center",
                data: legendData,
                y: "5%",
                itemWidth: 18,
                itemHeight: 12,
                textStyle: {
                    color: "#fff",
                    fontSize: 14
                },
            },
            toolbox: {
                orient: 'vertical',
                right: '1%',
                top: '20%',
                iconStyle: {
                    color: '#fff',
                    borderColor: '#fff',
                    borderWidth: 1,
                },
                feature: {
                    saveAsImage: {},
                    magicType: {
                        type: ['line','bar','stack','tiled']
                    }
                }
            },
            color: colors,
            grid: {
                left: '2%',
                top: "12%",
                bottom: "5%",
                right: "5%",
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function(params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(item => {
                        result += `${item.seriesName}: ${item.value}°C<br/>`;
                    });
                    return result;
                }
            },
            xAxis: {
                type: 'category',
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#6173A3'
                    }
                },
                axisLabel: {
                    interval: 0,
                    textStyle: {
                        color: '#9ea7c4',
                        fontSize: 12
                    }
                },
                axisTick: {
                    show: false
                },
                data: dates,
            },
            yAxis: {
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#9ea7c4',
                        fontSize: 12
                    }
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#6173A3'
                    }
                },
            },
            series: serieData
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    }

    function echart_2(highCount, normalCount, lowCount) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('chart_2'));
        var giftImageUrl = "";

        myChart.setOption({
            graphic: {
                elements: [{
                    type: 'image',
                    style: {
                        image: giftImageUrl,
                        width: 30,
                        height: 30
                    },
                    left: '73%',
                    top: 'center'
                }]
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['高温', '正常', '低温'],
                left:'27%'
            },
            grid: {
                left: '1%',
                right: '60%',
                top: '10%',
                bottom: '10%',
                containLabel: true,
            },
            xAxis: {
                type: 'value',
                position:'top',
                splitLine: {show: false},
                boundaryGap: [0, 0.01],
                axisTick: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#9ea7c4',
                        fontSize: 12
                    }
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#6173A3'
                    }
                },
            },
            yAxis: {
                type: 'category',
                data: ['高温','正常','低温'],
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#9ea7c4',
                        fontSize: 9
                    }
                },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#6173A3'
                    }
                },
            },
            series: [{
                name: '',
                itemStyle: {
                    normal: {
                        color: function(params) {
                            // build a color map as your need.
                            var colorList = [
                                '#C1232B','#B5C334','#FCCE10'
                            ];
                            return colorList[params.dataIndex]
                        },
                        shadowBlur: 20,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                type: 'bar',
                data: [highCount, normalCount, lowCount]
            },{
                type: 'pie',
                radius: [30, '80%'],
                center: ['75%', '50%'],
                roseType: 'radius',
                color: [ '#C1232B','#B5C334','#FCCE10'],
                data: [{
                    value: highCount,
                    name: '高温'
                }, {
                    value: normalCount,
                    name: '正常'
                }, {
                    value: lowCount,
                    name: '低温'
                }],
                label: {
                    normal: {
                        textStyle: {
                            fontSize: 14
                        },
                        formatter: function(param) {
                            return param.name + ':\n' + Math.round(param.percent) + '%';
                        }
                    }
                },
                labelLine: {
                    normal: {
                        smooth: true,
                        lineStyle: {
                            width: 2
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        shadowBlur: 30,
                        shadowColor: 'rgba(0, 0, 0, 0.4)'
                    }
                },

                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function(idx) {
                    return Math.random() * 200;
                }
            }]
        });
    }

    function echart_3(trainLoss, testLoss, trainRmse, testRmse, epochs) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('chart_3'));

        var option = {
            color: ["#036BC8", "#2EF7F3", "#FFA500", "#FF4500"],

            title: [{
                text: '训练过程指标',
                left: '1%',
                top: '6%',
                textStyle: {
                    color: '#fff'
                }
            }],
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                x: 300,
                top: '7%',
                textStyle: {
                    color: '#ffd285',
                },
                data: ['训练损失', '测试损失', '训练RMSE', '测试RMSE']
            },
            grid: {
                left: '1%',
                right: '28%',
                top: '16%',
                bottom: '6%',
                containLabel: true
            },
            toolbox: {
                "show": false,
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                "axisLine": {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                "axisTick": {
                    "show": false
                },
                axisLabel: {
                    textStyle: {
                        color: '#fff'
                    }
                },
                boundaryGap: false,
                data: epochs
            },
            yAxis: {
                "axisLine": {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                splitLine: {
                    show: false,
                    lineStyle: {
                        color: '#fff'
                    }
                },
                "axisTick": {
                    "show": false
                },
                axisLabel: {
                    textStyle: {
                        color: '#fff'
                    }
                },
                type: 'value'
            },
            series: [
                {
                    name: '训练损失',
                    smooth: true,
                    type: 'line',
                    symbolSize: 9,
                    symbol: 'circle',
                    data: trainLoss
                },
                {
                    name: '测试损失',
                    smooth: true,
                    type: 'line',
                    symbolSize: 9,
                    symbol: 'circle',
                    data: testLoss
                },
                {
                    name: '训练RMSE',
                    smooth: true,
                    type: 'line',
                    symbolSize: 9,
                    symbol: 'circle',
                    data: trainRmse
                },
                {
                    name: '测试RMSE',
                    smooth: true,
                    type: 'line',
                    symbolSize: 9,
                    symbol: 'circle',
                    data: testRmse
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    }
});